<template>
  <a-modal
    style="width: 50%"
    :title="titleMap[mode]"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :destroyOnClose="true"
    @cancel="handleCancel"
    :maskClosable="false">
    <div style="margin-top: 12px;">
      <a-form-model ref="ruleAddForm" :model="addForm" :rules="addRules">
        <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
          <a-input placeholder="请输入预算项目名称" v-model.trim="addForm.name" :max-length="40" />
        </a-form-model-item>
        <a-form-model-item label="上级预算项目" prop="parentProjectId" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-spin :spinning="spinning" tip="加载中...">
            <!-- @change="change" -->
            <a-select
              :show-search="false"
              placeholder="请选择上级预算项目"
              @popupScroll="popupScroll"
              optionFilterProp="children"
              v-model="addForm.parentProjectId"
              showSearch
              :allow-clear="true"
              @select="change"
              @search="onSearch"
              :field-names="{ label: 'name', value: 'projectId' }"
              :option="projectList"
              @blur="onBlur">
              <a-select-option v-for="(item, index) in projectList" :key="index" :value="item.projectId">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-spin>
        </a-form-model-item>
        <a-form-model-item label="所属类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryId">
          <a-tree-select
            v-model="addForm.categoryId"
            style="width: 100%"
            :dropdown-style="{ maxHeight: '220px', overflow: 'auto' }"
            :tree-data="treeData"
            placeholder="请选择所属类别"
            :replaceFields="replaceFields"
            tree-node-filter-prop="categoryName"
            :default-expanded-keys="addForm.categoryId"
            :allow-clear="true"
            :default-selected-keys="addForm.categoryId" />
        </a-form-model-item>
        <a-form-model-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sortOrder">
          <a-radio-group @change="sortChange" v-model="addForm.sortOrder">
            <a-radio :value="1">升序</a-radio>
            <a-radio :value="2">降序</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="计入汇总" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="includedIn">
          <a-radio-group @change="radioChange" v-model="addForm.includedIn">
            <a-radio :value="0">不计入</a-radio>
            <a-radio :value="1">计入</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="收支类型" prop="inOrOut" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-select placeholder="请选择收支类型" @select="onSelect" v-model="addForm.inOrOut" :allow-clear="true">
            <a-select-option :value="item.id" v-for="(item, index) in TypeList" :key="index">{{ item.name
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="description">
          <a-textarea :rows="4" v-model.trim="addForm.description" placeholder="请输入描述信息" :max-length="255" />
        </a-form-model-item>
      </a-form-model>
    </div>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">
        关闭
      </a-button>
      <a-button type="primary" :visible="visibleBtn" :loading="loadingBtn" @click="handleOk">
        保存
      </a-button>
    </template>
  </a-modal>
</template>
<script>

import { getProjectCate, addProjects, editProjects, getProjects } from '@/api/budget'
export default {
    components: {},
    data () {
        return {
            addRules: {
                name: [
                    { required: true, message: '请输入预算项目名称!', trigger: 'blur' }
                ],
                inOrOut: [
                    { required: true, message: '请选择收支类型!', trigger: 'change' }
                ],
                categoryId: [
                    { required: false, message: '请选择所属类别!', trigger: 'change' }
                ],
                includedIn: [
                    { required: true, message: '是否计入汇总!', trigger: 'change' }
                ],
                sortOrder: [
                    { required: true, message: '请选择排序方式!', trigger: 'change' }
                ]
            },
            replaceFields: { children: 'children', label: 'categoryName', value: 'categoryId', key: 'categoryId' },
            addForm: {
                name: '',
                description: '',
                categoryId: undefined,
                inOrOut: 1,
                includedIn: 0,
                // 1 升序  2降序
                sortOrder: 1,
                parentProjectId: undefined
                // summary:0
            },
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            },
            TypeList: [{ id: 1, name: '收入' }, { id: 2, name: '支出' }, { id: 3, name: '其它' }],
            visible: false,
            confirmLoading: false,
            loading: false,
            visibleBtn: false,
            loadingBtn: false,
            mode: 'add',
            titleMap: {
                add: '新增',
                edit: '编辑'
            },
            rowData: '',
            treeData: [],
            treeLoadData: true,

            // 项目预算数据
            projectList: [],
            pageNo: 1,
            max: false,
            spinning: false,
            pageSize: 10,
            searchWorld: '',
            total: 0
        }
    },
    mounted () {

    },
    methods: {
        // 加载预算项目数据
        loadDatas () {
            this.pageNo = 1
            var param = {
                current: this.pageNo,
                pageSize: this.pageSize,
                name: this.searchWorld,
                inOrOut: '',
                description: ''
            }
            getProjects(param).then((res) => {
                if (res.code == 200) {
                    this.projectList = res.data.datas
                    this.total = res.data.total
                }
            })
        },
        // 滚动条滚动监听方法
        async popupScroll (e) {
            const that = this
            const { target } = e
            const scrollHeight = target.scrollHeight - target.scrollTop // 滑动总高度
            const clientHeight = target.clientHeight // 滑动最低高度
            // 当下拉框滚动条到达底部的时候
            if (!this.max && scrollHeight < clientHeight + 2) {
                this.spinning = true
                // 数据起始条数
                this.pageNo++
                var newList = []
                var param = {
                    current: this.pageNo,
                    pageSize: this.pageSize,
                    name: this.searchWorld,
                    inOrOut: '',
                    description: ''
                }
                await getProjects(param).then((res) => {
                    if (res.code == 200) {
                        newList = res.data.datas
                        that.total = res.data.total
                        if (newList.length == 0) {
                            that.max = true
                        }
                    }
                })
                if (that.total != this.projectList.length) {
                    // 数据追加
                    this.projectList = this.projectList.concat(newList)
                }
                this.spinning = false
            }
        },
        // 下拉框搜索方法
        onSearch (val) {
            if (val.length != 0) {
                this.searchWorld = val
                this.projectList = []
                this.max = false
                this.loadDatas()
            } else {
                this.searchWorld = ''
                this.addForm.parentProjectId = undefined
                this.projectList = []
                this.max = false
                this.loadDatas()
            }
        },
        // 改变上级预算id
        change (val) {
            this.addForm.parentProjectId = val
        },
        onBlur () {
            this.searchWorld = ''
            this.projectList = []
            this.max = false
            this.loadDatas()
        },
        // 排序
        sortChange (e) {
            const { value } = e.target
            this.addForm.includedIn = value
        },
        // 是否计入汇总
        radioChange (e) {
            const { value } = e.target
            this.addForm.includedIn = value
        },
        // 收支类型
        onSelect (e) {
            this.addForm.inOrOut = e
        },

        // 显示
        open (mode = 'add') {
            this.mode = mode
            this.visible = true

            this.loadDatas()
            return this
        },
        // 获取行数据和id
        setData (row) {
            console.log(row)
            if (this.mode == 'edit') {
                this.addForm = row
                getProjectCate().then(res => {
                    this.treeLoadData = false
                    if (res.code == 200) {
                        this.treeData = res.data
                        let ProjectId = row.parentProjectId + ''
                        ProjectId = ProjectId == 'null' ? undefined : ProjectId
                        this.addForm.parentProjectId = ProjectId
                    }
                })
                // this.addForm.summary = row.includedIn
            } else {
                getProjectCate().then(res => {
                    this.treeLoadData = false
                    if (res.code == 200) {
                        this.treeData = res.data
                    }
                })
            }
            this.rowData = row
        },
        // 关闭
        handleCancel () {
            this.visible = false
            this.loadingBtn = false
            this.visibleBtn = false
            this.rowData = ''
            this.addForm = {
                name: '',
                code: '',
                description: '',
                categoryId: undefined,
                inOrOut: 1,
                projectId: '',
                includedIn: 0,
                sortOrder: 1
            }
            this.$emit('close')
        },
        // 确认
        handleOk () {
            this.loadingBtn = true
            this.visibleBtn = true
            this.$refs.ruleAddForm.validate(valid => {
                if (valid) {
                    const { name, description,
                        categoryId, inOrOut, includedIn, sortOrder, parentProjectId } = this.addForm
                    const par = {
                        name,
                        description,
                        categoryId: categoryId == undefined ? '' : Number(categoryId),
                        inOrOut,
                        includedIn,
                        sortOrder,
                        parentProjectId: parentProjectId == undefined ? '' : parentProjectId
                    }
                    if (this.mode == 'edit') par.projectId = this.rowData.projectId
                    const Api = this.mode == 'add' ? addProjects : editProjects
                    Api(par).then(res => {
                        if (res.code === 200) {
                            this.$notification['success']({
                                message: '提示',
                                description: '保存成功！',
                                duration: 8
                            })
                            this.visible = false
                            this.handleCancel()
                            this.$emit('success')
                        } else {
                            this.$notification['error']({
                                message: '提示',
                                description: res.message,
                                duration: 8
                            })
                        }
                        this.visibleBtn = false
                        this.loadingBtn = false
                    })
                } else {
                    this.loadingBtn = false
                    this.visibleBtn = false
                    return false
                }
            })
        }
    }
}
</script>
<style scoped lang="less" ></style>
